package com.yd.cfckc.task;

import com.yd.cfckc.util.CsvReader;
import com.yd.cfckc.util.RedisPool;
import com.yd.cfckc.util.SrvUtil;
import org.apache.log4j.Logger;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
import java.util.TimerTask;

/**
 * @author cuiyufeng
 * @email cuiyufeng1458@yundasys.com
 * @date 2020/10/16 3:55 下午
 */
public class SjdwTask extends TimerTask {


    private static Logger logger = Logger.getLogger(SjdwTask.class);
    private static boolean isRunning = true;
    private static JedisPool pool = RedisPool.getPool();
    private static Jedis jedis = pool.getResource();

    @Override
    public void run() {
        if (isRunning) {
            try {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");//20200712000000
                Calendar calendar = Calendar.getInstance();
                calendar.add(Calendar.DAY_OF_MONTH, -1);
                String now_time = sdf.format(calendar.getTime()) + "000000";
                System.out.println("now_time = " + now_time);
                String url = SrvUtil.getProperties().getProperty("url");
                String fileName = "cf_sjdw_datas_" + now_time;
                boolean flag = downLoadDealCsv(url, fileName, "GET", jedis);
                if (flag) {
                    logger.info("下载-处理总部sjdw数据over!");
                } else {
                    logger.error("下载-处理总部sjdw数据出现异常!");
                }
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
            }
        } else {
            logger.error("Sjdw 执行异常...");
        }
    }

    public static boolean downLoadDealCsv(String url, String fileName, String method, Jedis jedis) {
        boolean flag = false;
        String path = "/u02/data/cfCheckSjdwCache";
        String filePath = path + File.separator + fileName;
        File file = new File(path);
        String downLoadUrl = url + "/" + fileName + ".csv";
        System.out.println("downLoadUrl = " + downLoadUrl);
        if (!file.exists()) {
            file.mkdirs();
        }
        FileOutputStream fileOut = null;
        HttpURLConnection conn = null;
        InputStream inputStream = null;
        try {
            URL httpUrl = new URL(downLoadUrl);
            conn = (HttpURLConnection) httpUrl.openConnection();
            conn.setRequestMethod(method);
            conn.setDoInput(true);
            conn.setDoOutput(true);
            conn.setUseCaches(false);
            conn.connect();
            inputStream = conn.getInputStream();
            BufferedInputStream bis = new BufferedInputStream(inputStream);
            fileOut = new FileOutputStream(filePath);
            BufferedOutputStream bos = new BufferedOutputStream(fileOut);

            byte[] buf = new byte[4096];
            int length = bis.read(buf);

            while (length != -1) {
                bos.write(buf, 0, length);
                length = bis.read(buf);
            }
            bos.close();
            bis.close();
            conn.disconnect();
            readCsv(filePath, jedis);
            flag = true;
        } catch (Exception e) {
            flag = false;
            logger.error("下载-处理总部sjdw数据出现异常!");
            logger.error(e.getMessage());
        }
        return flag;
    }

    public static void readCsv(String filePath, Jedis jedis) throws IOException {
        CsvReader reader = null;
        Map<String, String> mapTemp = new HashMap<String, String>();
        reader = new CsvReader(filePath, ',', Charset.forName("UTF-8"));
        while (reader.readRecord()) {
            String[] dataArray = reader.getValues();
            if ((dataArray != null) && (dataArray.length >= 2)) {
                mapTemp.put(dataArray[0], dataArray[1]);
            }
        }
        logger.info("已解析:" + filePath);
        reader.close();
        File file = new File(filePath);
        if (file.exists()) {
            file.delete();
        }
        for (Map.Entry<String, String> entry : mapTemp.entrySet()) {
            jedis.set(entry.getKey(), entry.getValue());
        }
    }
}
